<?php

namespace app\system\controller;

use app\common\tool\Tool;
use app\system\model\AdminModel;
use think\Controller;
use think\facade\Cache;

class Login extends Controller
{
    use Tool;
    //token 过期时间
    private $token_expiration_time = 60 * 60 * 24 * 14;
    public function login(){
        $username = input('username');
        $password = input('password');
        if(!isset($username, $password)){
            return $this->returnJson(500, '管理员的用户名和密码必须都存在');
        }
        $admin = AdminModel::get(['username' => $username]);
        if(!$admin){
            return $this->returnJson(500, '用户不存在');
        }
        if($admin->status !== 1){
            return $this->returnJson(402, '用户被禁用');
        }
        if($admin->password !== md5($password)){
            return $this->returnJson(500, '用户名或密码错误');
        }

        //生成token
        $token = $this->getRandom(32);
        //设置缓存
        Cache::set($token,$admin->id,$this->token_expiration_time);
        //设置会话cookie,浏览器关闭则失效
        //cookie('base_admin_token', $token);
        return $this->returnJson(200, '登录成功', [
            'data' => $admin,
            'token' => $token
        ]);
    }

    public function logout(){
        $authorization = request()->header('Authorization');
        if(!$authorization){
            return $this->returnJson(500, '请在请求头中添加 Authorization token');
        }
        $admin = Cache::get($authorization);
        if(!$admin){
            return $this->returnJson(500, '该 token 没有登录或不存在,无需退出');
        }
        //session($authorization , null);
        Cache::rm($authorization);
        return $this->returnJson(200, '退出登录', [
            'data' => $admin,
            'token' => $authorization
        ]);

    }
}
